import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/GoodsDetail.dart';

import 'MerchantPage.dart';
import 'ServiceIndexPage.dart';

class GoodsListPage extends StatefulWidget {
  String gName;//按商品名称搜索
  int sort;//排序方式（0：默认权重  1：销量  2：上架时间）降序
  int type;//类型（0：根据商品名称搜索  1：根据类型搜索商品）
  int typeId;//类型ID
  GoodsListPage({Key key, this.title, this.gName, this.sort, this.type, this.typeId}) : super(key: key);

  final String title;

  @override
  _GoodsListPage createState() => _GoodsListPage(gName,sort,type,typeId);
}

class _GoodsListPage extends State<GoodsListPage> {
  FocusNode _focusNode = FocusNode(); // 焦点事件
  List<Widget> items = [Text("1"), Text("2"),Text("3"),Text("4"),Text("5"),Text("6")];
 // List goods = [{"gid":100,"gname":"苹果","gprice":100},{"gid":101,"gname":"苹果1","gprice":200},{"gid":102,"gname":"苹果2","gprice":300},{"gid":103,"gname":"苹果3","gprice":400},];
  List goods=[];//商品集合
  int page=1;//页数
  String gName = "";//商品名称
  int sort = 0;//排序方式
  int type = 0;//搜索类型(0：搜索所有  1：根据商家类型搜索)
  int typeId;//类型ID
  // 构造函数
  _GoodsListPage(gName,sort,type,typeId){
    this.gName = gName;
    this.sort = sort;
    this.type = type;
    this.typeId = typeId;
    _onLoading();
  }
  // 上拉加载控制器
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  // 刷新时调用
  void _onRefresh() async{
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }
  // 加载数据的函数
  void _onLoading() async{
    // monitor network fetch
    // await Future.delayed(Duration(milliseconds: 1000));
    // Response response = await Dio().get("http://xllm.szghrj.com:8082/app/goods/searchAllGoods?limit=10&page=${page}");
    // var x = json.decode(response.toString());
    var x;
    if(type==0){
      // x = await HttpUtil().get("/app/goods/searchAllGoods?limit=10&page=${page}&gName="+gName+"&sort=${sort}");
      x = await HttpUtil().get("/waimai/merchant/searchMerchant?limit=10&page=${page}&mName="+gName+"&sort=${sort}");
    }else{
      // x = await HttpUtil().get("/app/goodsType/getGoodsTypeAllGoods?limit=10&page=${page}&id=${typeId}&gName="+gName);
      x = await HttpUtil().get("/waimai/merchant/searchMerchant?limit=10&page=${page}&typeId=${typeId}&mName="+gName);
    }
    page++;
    if(x['code']==200){
      goods.addAll(x['data']);
    }
    if(x['data'].length<1){
      _refreshController.loadNoData();
      return;
    }
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    if(mounted){
      setState(() {});
      _refreshController.loadComplete();
    }
  }

  GestureDetector _showGoods(item){
    return GestureDetector(
      child: Container(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Image.network("http://xllm.szghrj.com:8082${item['gimages']}",width: 70,height: 70,),
            CachedNetworkImage(imageUrl: Config.getInstance().getHost()+item['picture'],width: ScreenUtil().setWidth(110),height: ScreenUtil().setHeight(110),),
            Container(
              constraints: BoxConstraints(maxWidth: 280,maxHeight: 80),
              padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
              // alignment: Alignment(-1,0),
              // decoration: new BoxDecoration(color: Colors.black),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(item['mname'],maxLines: 1,style: TextStyle(fontSize: 18,fontWeight: FontWeight.w500),),
                  // Text(item['jianjie']),
                  // Expanded(child: Text(item['jianjie'])),
                  Container(
                    width: ScreenUtil().setWidth(280),
                    height: ScreenUtil().setHeight(45),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(item['jianjie'],maxLines: 2,style: TextStyle(fontSize: 14),),
                        )
                      ],
                    ),
                  ),
                  // Text("￥${item['gprice'].toString()}"),
                ],
            ),),
          ],
        ),
      ),
      behavior: HitTestBehavior.opaque,
      onTap: (){
        String merchantTypeId;//商家类型ID
        if(type == 0){
          // List typeList = item['mtype'].toString().split(",");
          // merchantTypeId = typeList[0];
          merchantTypeId = item['type'];
        }
        Navigator.push(
          context,
          MaterialPageRoute(
              // builder:(context)=>GoodsDetail(gid:item['gid']),
            builder:(context)=>item['isFuwu']==0 ? MerchantPage(merchantId: item['id'],merchantTypeId: merchantTypeId,) : ServiceIndexPage(mId: item['id']),
          )
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // title: Text("商品列表"),
        automaticallyImplyLeading: false,
        backgroundColor: Colors.white,
        title: Container(  // 搜索区
          // height: ScreenUtil().setHeight(100),
          // padding: EdgeInsets.only(left: 10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(30)) ,
            border: Border.all(color: Colors.orange , width: 1) ,
          ),
          child: Row(children: [
            Icon(Icons.search,color: Colors.orange,),
            Expanded(child: TextField(
              autofocus: true,
              decoration: InputDecoration(
                hintText: "搜索店家、餐名",
                border: InputBorder.none,
              ),
              onChanged: (text){
                gName = text;
              },
            )),
            GestureDetector(
              child: Container(
                padding: EdgeInsets.fromLTRB(14, 5, 14, 5),
                child: Text("搜索",style: TextStyle(color: Colors.white),),
                decoration: BoxDecoration(
                  color: Colors.orange,
                  borderRadius: BorderRadius.all(Radius.circular(20)) ,
                  border: Border.all(color: Colors.black , width: 0) ,
                ),
              ),
              onTap: (){
                goods = [];
                page=1;
                setState(() {});
                _onLoading();
              },)
          ],),
        ),
      ),
      body: SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context,LoadStatus mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("上拉加载");
            }
            else if(mode==LoadStatus.loading){
              body =  CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("加载失败！点击重试！");
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("松手,加载更多!");
            }
            else{
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.builder(
          itemBuilder: (c, i) => Card(child: _showGoods(goods[i])),
          // itemExtent: 100.0,
          itemCount: goods.length,
        ),
      ),
    );
  }
}